package com.apobates.forum.thrones.admin.controller;

import com.apobates.forum.core.ImageIOMeta;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.core.entity.BoardGroup;
import com.apobates.forum.core.service.BoardGroupService;
import com.apobates.forum.thrones.admin.controller.form.BoardGroupForm;
import com.apobates.forum.thrones.admin.controller.helper.AdminUtils;
import com.apobates.forum.thrones.admin.exception.ResourceNotFoundException;
import com.apobates.forum.utils.lang.CommonBean;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;

/**
 * 版块卷控制器
 *
 * @author xiaofanku@live.cn
 * @since 20190321
 */
@Controller
@RequestMapping(value = "/board/group")
public class AdminBoardGroupController {
    @Autowired
    private BoardGroupService boardGroupService;
    @Autowired
    private ImageIOMeta imageIOMeta;
    private final static Logger logger = LoggerFactory.getLogger(AdminBoardGroupController.class);
    
    //版块组(卷)
    @GetMapping(path = "/")
    public String listPage(HttpServletRequest request, Model model) {
        List<BoardGroup> rs = boardGroupService.getAll().collect(Collectors.toList());
        rs.add(BoardGroup.defaultInstance()); //默认版块组
        model.addAttribute("rs", rs);
        return "admin/board_volumes/index";
    }
    
    //编辑版块组(卷)
    @GetMapping(path = "/edit")
    public String boardVolumesForm(
            @RequestParam(name = "id", required = false, defaultValue = "-1") int id,
            HttpServletRequest request,
            Model model) {
        if (id == 0) {
            throw new ResourceNotFoundException("默认版块组(卷)不需要编辑");
        }
        BoardGroupForm form = new BoardGroupForm();
        BoardGroup bg = boardGroupService.get(id).orElse(BoardGroup.empty());
        form.setRecord(id);
        form.setStatus(bg.isStatus());
        form.setTitle(bg.getTitle());
        form.setDescription(bg.getDescription());
        form.setImageAddr(bg.getImageAddr()); //编码后的图标图片地址|解码由标签负责
        form.setRanking(bg.getRanking() + "");
        model.addAttribute("form", form);
        return "admin/board_volumes/edit";
    }
    
    @PostMapping(path = "/edit")
    public String boardVolumesAction(
            HttpServletRequest request, 
            @Valid @ModelAttribute("form") BoardGroupForm form, 
            BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("form", form);
            return "admin/board_volumes/edit";
        }
        BoardGroup bg = new BoardGroup();
        bg.setTitle(form.getTitle());
        bg.setDescription(form.getDescription());
        bg.setStatus(form.getBooleanStatus());
        bg.setRanking(form.getIntegerRanking());
        //------------------------------------------------------------编码图标图片的地址
        String icoImageAddr = form.getEncodeIcoAddr(imageIOMeta).orElse(null);
        if (null != icoImageAddr) {
            bg.setImageAddr(icoImageAddr);
        }
        //------------------------------------------------------------
        boolean symbol;
        if (form.isUpdate()) {
            symbol = boardGroupService.edit(form.getIntegerRecord(), bg).orElse(false);
        } else {
            symbol = boardGroupService.create(bg.getTitle(), bg.getDescription(), bg.getImageAddr(), bg.isStatus(), bg.getRanking()).isPresent();
        }
        if (symbol) {
            return "redirect:/board/group/";
        }
        model.addAttribute("errors", form.getActionTitle() + "版块组(卷)操作失败");
        model.addAttribute("form", form);
        return "admin/board_volumes/edit";
    }
    //所有组(卷)
    @GetMapping(path = "/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<Integer, String> getAllForJson(HttpServletRequest request, Model model) {
        //包含所有状态的还有默认的
        return boardGroupService.getAllContainsDefault().collect(Collectors.toMap(BoardGroup::getId, BoardGroup::getTitle));
    }
    //查看指定的版块组(卷)的名称
    @GetMapping(path = "/list.json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<Integer, String> getAllForIdJson(
            @RequestParam("ids") String idString,
            HttpServletRequest request,
            Model model) {
        return boardGroupService.getAllById(AdminUtils.toIntegerSet(idString));
    }
    //加载版块组的标题
    @GetMapping(path = "/title", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public CommonBean getBoardGroupTitle(
            @RequestParam("id") int id,
            HttpServletRequest request,
            Model model) {
        if (id == -1) {
            return new CommonBean(-1, "所有");
        }
        if (id == 0) {
            return new CommonBean(0, "默认版块组");
        }
        String title = boardGroupService.get(id).map(BoardGroup::getTitle).orElse("版块组(卷)");
        return new CommonBean(id, title);
    }
}